package com.tlgen.caffeine.service.impl;

import com.github.benmanes.caffeine.cache.Cache;
import com.tlgen.caffeine.model.SysUser;
import com.tlgen.caffeine.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StopWatch;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ConcurrentMap;

/*
 *@title SysUserServiceImp
 *@description
 *@author ta151486
 *@version 1.0
 *@create 2023/12/18 10:11
 */
@Slf4j
@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private Cache<String, Object> cache;

    @Override
    public Object save() {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        // 存 8000000 条数据
        List<SysUser> userList = new ArrayList<>();
        for (int i = 0; i < 8000000; i++) {
            String id = UUID.randomUUID().toString();
            SysUser user = SysUser.builder()
                    .id(id)
                    .username("小e" + id.substring(0, 5))
                    .mobile("13617786374")
                    .email(id.substring(4, 6) + "@163.com")
                    .gender(1)
                    .build();
            userList.add(user);
        }
        cache.put("userList", userList);
        stopWatch.stop();
        log.info("\nsave 总耗时: {}", stopWatch.getTotalTimeMillis());
        return "SUCCESS";
    }

    @Override
    public Object select() {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        Collection<@NonNull Object> values = cache.asMap().values();
        @NonNull ConcurrentMap<@NonNull String, @NonNull Object> map = cache.asMap();
        stopWatch.stop();
        System.out.println(values.size());
        System.out.println(map.size());
        log.info("\nselect 总耗时: {}", stopWatch.getTotalTimeMillis());
        cache.invalidateAll();
        return "SUCCESS";
    }
}
